﻿using System.Linq;

namespace NiuX.LightServer.Options
{
    /// <summary>
    /// 跨域选项
    /// </summary>
    public class CorsOptions
    {
        public string AccessControlAllowOrigins { get; set; } = "";

        public bool AccessControlAllowCredentials { get; set; }

        public string AccessControlAllowMethods { get; set; } = "";

        public string AccessControlAllowHeaders { get; set; } = "";

        public string AccessControlExposeHeaders { get; set; } = "";

        public int? AccessControlMaxAge { get; set; }

        public bool IsAllAccessControlAllowOrigins => AccessControlAllowOrigins == "*";

        public bool IsAllowAll { get; set; }



        /// <summary>
        /// 是否允许源
        /// </summary>
        /// <param name="origin"></param>
        /// <returns></returns>
        public bool IsAllowOrigin(string origin)
        {
            if (AccessControlAllowOrigins == "*")
            {
                return true;
            }

            return AccessControlAllowOrigins.Split(',').Contains(origin);
        }

        /// <summary>
        /// 是否允许方法
        /// </summary>
        /// <param name="method"></param>
        /// <returns></returns>
        public bool IsAllowMethod(string method)
        {
            if (AccessControlAllowMethods == "*")
            {
                return true;
            }

            return AccessControlAllowMethods.Split(',').Contains(method);
        }

        /// <summary>
        /// 是否允许头部
        /// </summary>
        /// <param name="header"></param>
        /// <returns></returns>
        public bool IsAllowHeader(string header)
        {
            if (AccessControlAllowHeaders == "*")
            {
                return true;
            }

            var headers = header?.Split(',');
            var allowHeaders = AccessControlAllowHeaders.Split(',');

            if (headers == null)
            {
                return false;
            }

            foreach (var accessHeader in headers)
            {
                if (!allowHeaders.Contains(accessHeader))
                {
                    return false;
                }
            }

            return true;
        }
    }
}